package com.tyler.order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import javax.crypto.MacSpi;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author: TylerZhong
 * @description:
 */
public class OrderProducer {
    public static void main(String[] args) throws UnsupportedEncodingException, MQClientException, MQBrokerException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("orderProducerGroup");
        producer.setNamesrvAddr("192.168.56.191:9876");
        producer.start();

        for (int i = 0; i < 10; i++) {
            int orderId = i;
            for (int j = 0; j <= 5; j++) {
                Message message = new Message("OrderTopicTest", "order_" + orderId, "KEY" + orderId, ("order_" + orderId + " tep " + j).getBytes(RemotingHelper.DEFAULT_CHARSET));

                SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        Integer id = (Integer) arg;
                        int index = id % mqs.size();
                        return mqs.get(index);
                    }
                }, orderId);
                System.out.printf("%s%n", sendResult);
            }
        }

        producer.shutdown();
    }
}
